<template>
  <div class="stats-container">
    <div class="page-header">
      <div class="page-title">数据统计</div>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
        <el-button type="primary" @click="refreshStats">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <div class="page-content">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon task-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">总任务数</div>
                  <div class="stats-card-value">{{ overviewStats.total_tasks }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon success-icon">
                  <el-icon><Check /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">成功同步次数</div>
                  <div class="stats-card-value">{{ overviewStats.success_syncs }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon error-icon">
                  <el-icon><WarningFilled /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">失败同步次数</div>
                  <div class="stats-card-value">{{ overviewStats.failed_syncs }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon data-icon">
                  <el-icon><DataLine /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">同步数据总量</div>
                  <div class="stats-card-value">{{ formatNumber(overviewStats.total_records) }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 图表区域 -->
      <div class="stats-charts">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>同步任务执行趋势</span>
                </div>
              </template>
              <div class="chart-container" id="syncTrendChart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>同步任务状态分布</span>
                </div>
              </template>
              <div class="chart-container" id="syncStatusChart"></div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="chart-row">
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>数据源类型分布</span>
                </div>
              </template>
              <div class="chart-container" id="datasourceTypeChart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>任务执行时长TOP5</span>
                </div>
              </template>
              <div class="chart-container" id="taskDurationChart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 任务执行统计表格 -->
      <el-card shadow="hover" class="stats-table-card">
        <template #header>
          <div class="card-header">
            <span>任务执行统计</span>
          </div>
        </template>
        <el-table
          v-loading="loading"
          :data="taskStats"
          border
          style="width: 100%"
        >
          <el-table-column prop="task_name" label="任务名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="total_executions" label="执行次数" width="100" align="center" />
          <el-table-column prop="success_executions" label="成功次数" width="100" align="center" />
          <el-table-column prop="failed_executions" label="失败次数" width="100" align="center" />
          <el-table-column prop="success_rate" label="成功率" width="100" align="center">
            <template #default="{ row }">
              {{ calculateSuccessRate(row.success_executions, row.total_executions) }}
            </template>
          </el-table-column>
          <el-table-column prop="avg_duration" label="平均耗时" min-width="100" align="center">
            <template #default="{ row }">
              {{ formatDuration(row.avg_duration) }}
            </template>
          </el-table-column>
          <el-table-column prop="total_records" label="同步记录数" min-width="120" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.total_records) }}
            </template>
          </el-table-column>
          <el-table-column prop="last_execution_time" label="最近执行时间" min-width="180" show-overflow-tooltip />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Document, Check, WarningFilled, DataLine } from '@element-plus/icons-vue'
import { getOverviewStats, getTaskStats, getSyncTrend, getSyncStatusDistribution, getDatasourceTypeDistribution, getTaskDurationTop } from '@/api/stats'
import * as echarts from 'echarts'

const loading = ref(false)
const dateRange = ref([])
const overviewStats = ref({
  total_tasks: 0,
  success_syncs: 0,
  failed_syncs: 0,
  total_records: 0
})
const taskStats = ref([])

// 图表实例
let syncTrendChart = null
let syncStatusChart = null
let datasourceTypeChart = null
let taskDurationChart = null

// 查询参数
const queryParams = reactive({
  start_date: '',
  end_date: ''
})

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.start_date = val[0]
    queryParams.end_date = val[1]
  } else {
    queryParams.start_date = ''
    queryParams.end_date = ''
  }
  
  // 刷新统计数据
  refreshStats()
}

// 刷新统计数据
const refreshStats = () => {
  getOverview()
  getTaskStatistics()
  getSyncTrendData()
  getSyncStatusData()
  getDatasourceTypeData()
  getTaskDurationData()
}

// 获取概览统计
const getOverview = async () => {
  loading.value = true
  try {
    const res = await getOverviewStats(queryParams)
    overviewStats.value = res.data
  } catch (error) {
    console.error('获取概览统计失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取任务统计
const getTaskStatistics = async () => {
  loading.value = true
  try {
    const res = await getTaskStats(queryParams)
    taskStats.value = res.data
  } catch (error) {
    console.error('获取任务统计失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取同步趋势数据
const getSyncTrendData = async () => {
  try {
    const res = await getSyncTrend(queryParams)
    nextTick(() => {
      initSyncTrendChart(res.data)
    })
  } catch (error) {
    console.error('获取同步趋势数据失败:', error)
  }
}

// 获取同步状态分布数据
const getSyncStatusData = async () => {
  try {
    const res = await getSyncStatusDistribution(queryParams)
    nextTick(() => {
      initSyncStatusChart(res.data)
    })
  } catch (error) {
    console.error('获取同步状态分布数据失败:', error)
  }
}

// 获取数据源类型分布数据
const getDatasourceTypeData = async () => {
  try {
    const res = await getDatasourceTypeDistribution(queryParams)
    nextTick(() => {
      initDatasourceTypeChart(res.data)
    })
  } catch (error) {
    console.error('获取数据源类型分布数据失败:', error)
  }
}

// 获取任务执行时长TOP数据
const getTaskDurationData = async () => {
  try {
    const res = await getTaskDurationTop(queryParams)
    nextTick(() => {
      initTaskDurationChart(res.data)
    })
  } catch (error) {
    console.error('获取任务执行时长TOP数据失败:', error)
  }
}

// 初始化同步趋势图表
const initSyncTrendChart = (data) => {
  if (!syncTrendChart) {
    syncTrendChart = echarts.init(document.getElementById('syncTrendChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['成功', '失败']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成功',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: data.success,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '失败',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: data.failed,
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  syncTrendChart.setOption(option)
}

// 初始化同步状态分布图表
const initSyncStatusChart = (data) => {
  if (!syncStatusChart) {
    syncStatusChart = echarts.init(document.getElementById('syncStatusChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '同步状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  syncStatusChart.setOption(option)
}

// 初始化数据源类型分布图表
const initDatasourceTypeChart = (data) => {
  if (!datasourceTypeChart) {
    datasourceTypeChart = echarts.init(document.getElementById('datasourceTypeChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '数据源类型',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  datasourceTypeChart.setOption(option)
}

// 初始化任务执行时长TOP图表
const initTaskDurationChart = (data) => {
  if (!taskDurationChart) {
    taskDurationChart = echarts.init(document.getElementById('taskDurationChart'))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          return formatDuration(value)
        }
      }
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.task_name)
    },
    series: [
      {
        name: '平均执行时长',
        type: 'bar',
        data: data.map(item => item.avg_duration),
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  taskDurationChart.setOption(option)
}

// 计算成功率
const calculateSuccessRate = (success, total) => {
  if (total === 0) return '0%'
  const rate = (success / total) * 100
  return `${rate.toFixed(2)}%`
}

// 格式化数字
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

// 格式化持续时间
const formatDuration = (seconds) => {
  if (!seconds) return '0秒'
  
  seconds = Number(seconds)
  
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds}秒`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = seconds % 60
    return `${hours}时${minutes}分${remainingSeconds}秒`
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  if (syncTrendChart) syncTrendChart.resize()
  if (syncStatusChart) syncStatusChart.resize()
  if (datasourceTypeChart) datasourceTypeChart.resize()
  if (taskDurationChart) taskDurationChart.resize()
}

onMounted(() => {
  // 设置默认日期范围为最近30天
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  dateRange.value = [formatDate(start), formatDate(end)]
  queryParams.start_date = dateRange.value[0]
  queryParams.end_date = dateRange.value[1]
  
  // 获取统计数据
  refreshStats()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (syncTrendChart) syncTrendChart.dispose()
  if (syncStatusChart) syncStatusChart.dispose()
  if (datasourceTypeChart) datasourceTypeChart.dispose()
  if (taskDurationChart) taskDurationChart.dispose()
})
</script>

<style lang="scss" scoped>
.stats-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .page-content {
    .stats-cards {
      margin-bottom: 20px;
      
      .stats-card {
        height: 120px;
        
        .stats-card-content {
          display: flex;
          align-items: center;
          height: 100%;
          
          .stats-card-icon {
            width: 64px;
            height: 64px;
            border-radius: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 16px;
            
            .el-icon {
              font-size: 32px;
              color: #fff;
            }
            
            &.task-icon {
              background-color: #409EFF;
            }
            
            &.success-icon {
              background-color: #67C23A;
            }
            
            &.error-icon {
              background-color: #F56C6C;
            }
            
            &.data-icon {
              background-color: #E6A23C;
            }
          }
          
          .stats-card-info {
            .stats-card-title {
              font-size: 14px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .stats-card-value {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
            }
          }
        }
      }
    }
    
    .stats-charts {
      margin-bottom: 20px;
      
      .chart-row {
        margin-top: 20px;
      }
      
      .chart-card {
        .chart-container {
          height: 300px;
        }
      }
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>